var Rules =
{
    winningStroke  : null, /* TODO: should not be a memeber of this object */
    
    isMoveLegal : function(_move)
    {
        /* TODO: get rid of the double access to getBoard and getLocation */
        if (_move.getPlayer() === null || _move.getBoard() === null || _move.getLocation() === null)
            return 0;

        var board = _move.getBoard();
        var location = _move.getLocation();

        return !board.isLocationOccupied(location);
    },
    
    getNextPlayer : function(players, currentPlayer)
    {
        return (currentPlayer.getType() === "X") ? players[1] : players[0];
    },
    
    createGamePlayers : function()
    {
        // Player index 0 is always 'X'.
        // Player index 1 is always 'O'.
        var players = new Array(2);
        players[0] = (new Player()).setType("X");
        players[1] = (new Player()).setType("O");
        return players;
    },
    
    isGameDraw : function(board)
    {
        if (!this.isGameWin(board))
        {
            for (var i = 1 ; i <= 9 ; ++i)
            {
                var location = new Location(i); // TODO: move allocation outside of loop 
                if (board.getPieceByLocation(location) === "e" )
                {
                    return false;
                }
            }
            return true;
        }
        return false;
    },
    
    isGameWin : function(board)
    {

        return this.isBoardLineComplete(board, 1,2,3)
                        || this.isBoardLineComplete(board, 4,5,6)
                        || this.isBoardLineComplete(board, 7,8,9)
                        || this.isBoardLineComplete(board, 1,4,7)
                        || this.isBoardLineComplete(board, 2,5,8)
                        || this.isBoardLineComplete(board, 3,6,9)
                        || this.isBoardLineComplete(board, 1,5,9)
                        || this.isBoardLineComplete(board, 3,5,7);
    },
    
    getWinningStroke : function()
    {
        return Rules.winningStroke;  /* TODO: should not be a memeber of this object */
    },
    
    isBoardLineComplete : function(board, location1, location2, location3)
    {
        var _location1 = new Location(location1);
        var _location2 = new Location(location2);
        var _location3 = new Location(location3);

        var piece1 = board.getPieceByLocation(_location1);
        var piece2 = board.getPieceByLocation(_location2);
        var piece3 = board.getPieceByLocation(_location3);

        if (piece1 !== "e" && piece2 !== "e" && piece3 !== "e")
        {
            if (piece1 === piece2 && piece2 === piece3)
            {
                Rules.winningStroke = new Array(3);  /* TODO: should not be a memeber of this object */
                Rules.winningStroke[0] = location1;
                Rules.winningStroke[1] = location2;
                Rules.winningStroke[2] = location3;
                return true;
            }
        }

        return false;
    }    
};